# -*- encoding:utf-8 -*-
import MySQLdb
import MySQLdb.cursors

class DB():

    """数据库管理类"""
    def __init__(self, host, port, user, passwd, name):
        self.db = MySQLdb.connect(
            host = host,
            port = port,
            user = user,
            passwd = passwd,
            db = name,
            charset='utf8',
            cursorclass = MySQLdb.cursors.DictCursor)
        self.cursor = self.db.cursor()

    def get_all(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def get_one(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchone()

    def insert(self, sql):
        self.cursor.execute(sql)
        self.db.commit()
        return self.cursor.lastrowid

    def update(self, sql):
        row = self.cursor.execute(sql)
        self.db.commit()
        return row

    def clear(self):
        self.cursor.close()
        self.db.close()

